<?php

namespace App\Http\Controllers\Admin\Finance\Service;

use App\Exceptions\AdminErrorException;
use App\Exceptions\WechatException;
use App\Http\Controllers\Admin\Finance\Repository\Withdraw as WithdrawRepository;
use App\Http\Controllers\Admin\Member\Repository\Member;
use App\Repositories\PacketRepository;
use App\Repositories\PageRepository;
use App\Repositories\WechatBroadcast;
use Illuminate\Http\Request;

class Withdraw
{
    /**
     * 发布状态 1启用 2禁用
     */
    const STATUS_APPROVE_AWAIT = 1;
    const STATUS_APPROVE = 2;
    const STATUS_REFUSE = 3;
    const STATUS_PAY = 4;
    const STATUS_AUTO_PAY = 5;

    /**
     *时间
     */
    const APPLY_TIME = 'apply_time';
    const APPROVE_TIME = 'approve_time';
    const PAY_TIME = 'pay_time';
    /*
     *
     */
    const TYPE_SYS = 1;//系统添加
    const TYPE_USER = 2;//用户申请


    /**
     * Http请求
     * @var $request
     */
    private $request;
    private $repository;
    private $account;

    public function __construct ()
    {
        $this->repository = new WithdrawRepository();
        $this->account = new Account();
    }
    //常用参数操作
    /**
     * @param $status
     *
     * @return mixed
     */
    public function getStatusString($status){
        $statusList =  $this->getStatusList();
        return $statusList[$status];
    }


    /**
     * @return array
     */
    public static function getTypeList(){
        return [
            self::TYPE_SYS =>  '系统添加',
            self::TYPE_USER =>  '用户申请',
        ];
    }

    public function getTypeString($status){
        $statusList =  $this->getTypeList();
        return $statusList[$status];
    }


    /**
     * @return array
     */
    public static function getStatusList(){
        return [
            self::STATUS_APPROVE_AWAIT =>  '待审批',
            self::STATUS_APPROVE =>  '已审批',
            self::STATUS_REFUSE =>  '已驳回',
            self::STATUS_PAY =>  '已打款',
            self::STATUS_AUTO_PAY =>  '小额自动提现'
        ];
    }

    //读操作

    public function getWithdraw($id){
        return $this->repository->with(['member'])->find($id);
    }

    /**
     * @param Request $request
     *
     * @return $this|\Illuminate\Database\Eloquent\Builder|static
     */
    public function getPageList(Request $request,$order=false){
        $this->request = $request;
        $model=$this->repository->with(['member'=>function($query) use ($request){
            if(isset($this->request->searchKey)){
                $query=$query->where('nickname','like', '%'.$this->request->searchKey.'%');
            }
        }]);
        //状态
        if(isset($this->request->status)&&$this->request->status!=''){
            $model=$model->where('status','=',$this->request->status);
        }
        //时间
//        if(isset($this->request->searchTime)&&$this->request->searchTime!=''){
//            //申请时间
//            $timeArray=explode('~',$this->request->searchTime);
//            $start_time=trim($timeArray[0]);
//            $end_time=trim($timeArray[1]);
//            $searchTimeType = isset($this->request->searchTimeType)?$this->request->searchTimeType:1;
//            $model=$model->whereBetween('created_at',[$start_time,$end_time]);
//        }
        $model=$model->orderBy('apply_time','desc');
        if($order==true){
            $model = $model->orderBy('sort','ASC');
        }
        $model=$model->paginate($this->request->limit);

        if($model){
            $model=$model->toArray();
        }
        foreach ($model['data'] as $k=>&$v){
            $v['status_name'] = self::getStatusList()[$v['status']];
            $v['nickname'] = $v['member']['nickname'];

        }
        return $model;
    }

    //写操作
    /**
     * @param $post
     */
    public function withdraw($post){
        //改变用户账户
        Member::where('id',$post['member_id'])->decrement('wallet_push_money',$post['price']);
        Member::where('id',$post['member_id'])->increment('wallet_used_push_money',$post['price']);
        //加入提现记录
        $model = $this->repository;
        $model->price = $post['price'];
        $model->type = self::TYPE_SYS;
        $model->member_id = $post['member_id'];
        $model->status = self::STATUS_PAY;
        $model->desc = $post['desc'];
        $model->bank_id = $post['bank_id'];
        $model->username = $post['username'];
        $model->pay_time = date('Y-m-d H:i:s',time());
        $model->save();
        //在财务表增加记录
        $this->account->account_log($post['member_id'],Account::WITHDRAW,$post['price']);
        return true;
    }

    public function refuse($id,$desc){
        $model = $this->repository->find($id);
        if($model->status!=self::STATUS_APPROVE_AWAIT&&$model->status!=self::STATUS_APPROVE){
            return false;
        }else{

            $model->refuse_time = date('Y-m-d H:i:s',time());
            $model->refuse_reason = $desc;
            $model->status = self::STATUS_REFUSE;
        }

        $model->save();
        //退钱
        Member::where('id',$model->member_id)->increment('wallet_push_money',$model->price+$model->poundage);
        Member::where('id',$model->member_id)->decrement('wallet_used_push_money',$model->price+$model->poundage);
        //
        $this->account->account_log($model->member_id,Account::WITHDRAW_REFUSE,$model->price);

    }
    public function setApprove($id,$desc){
        $model = $this->repository->where('id',$id)->where('status',self::STATUS_APPROVE_AWAIT)->first();
        if($model){
                return $this->repository->where('id',$id)
                    ->where('status',self::STATUS_APPROVE_AWAIT)
                    ->update([
                        'status'=>self::STATUS_APPROVE,
                        'approve_time'=>date('Y-m-d H:i:s',time()),
                        'desc'=>$desc
                    ]);
        }else{
            return false;
        }

    }
    public function setPay($id,$desc){
        $model=$this->repository->where('id',$id)->first();

        $member=Member::find($model->member_id);

     /*   //通过银行卡发放零钱
        $url = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo='.$model->bank_id.'&cardBinCheck=true';
        $res = json_decode(file_get_contents($url),true);
         $bankList=\Config::get('bank');

         if(isset($res['bank'])&&isset($bankList[$res['bank']])){
            $bankCode=$bankList[$res['bank']];
         }else{
             throw new WechatException('银行卡暂不支持或银行卡号不对');
         }*/
       /* $app=new \App\Service\WechatBankCard();
        $params= [
            'bank_code'=>$bankCode,
            'partner_trade_no'=>$app->outTradeNo(),
            'enc_bank_no'=>$model->bank_id,
            'enc_true_name'=>$model->username,
            'amount'=>(int)($model->price*100),
            'desc'=>'提现申请'];
        $app->toBankCard($params);*/
        $pageRepository=new PacketRepository();
        $pageRepository->merchantPay(Member::find($model->member_id),$model->price);

        //发送微信通知
        $wechat=new WechatBroadcast();
        $wechat->sendOne($member->openid,'您的提现金额为'.$model->price.'请注意查收');
        return $this->repository->where('id',$id)->whereIn('status',[self::STATUS_APPROVE,self::STATUS_APPROVE_AWAIT])->update([
            'status'=>self::STATUS_PAY,
            'desc'=>$desc,
            'partner_trade_no'=>'',
            'pay_time'=>date('Y-m-d H:i:s',time())
        ]);
    }

}
